package cn.eeepay.boss.system;

import cn.eeepay.framework.util.Constants;
import cn.eeepay.framework.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Deque;
import java.util.concurrent.LinkedBlockingDeque;

public class DynamicDataSourceHolder {

    private DynamicDataSourceHolder(){}

    private static final ThreadLocal<Deque<String>> local = new ThreadLocal<>();

    public static ThreadLocal<Deque<String>> getLocal() {
        return local;
    }

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceHolder.class);

    public static void putDataSource(String dataSource) {
        Deque<String> queue = local.get();
        if (queue == null) {
            queue = new LinkedBlockingDeque<>();
            local.set(queue);
        }
        if(StringUtil.isBlank(dataSource)) {
            dataSource = Constants.DATA_SOURCE_MASTER;
        }
        queue.addLast(dataSource);
        log.info("切换到{}...", dataSource);
    }

    //清除local中的值，用于数据源切换失败的问题
    public static void clearDbType() {
        Deque<String> queue = local.get();
        if (queue != null && !queue.isEmpty()) {
            queue.removeLast();
            if (queue.isEmpty()) {
                local.set(null);
            }
        }
    }

    public static String getDataSource() {
        Deque<String> queue = local.get();
        return queue != null ? queue.peekLast() : null;
    }
}
